from django.db.models import F
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND
from rest_framework.viewsets import GenericViewSet, ModelViewSet

from .ArtcilePagination import MyPagination
from .models import *
from .serializers import *


# GenericViewSet 什么方法都没写
# ListModelMixin查询所有的数据
class LabelViewSet(GenericViewSet, ListModelMixin):
    queryset = Label.objects.all()
    serializer_class = LabelSerializer
    permission_classes = [IsAuthenticated]


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = MyPagination

    def get_queryset(self):
        if self.action in ['list', 'retrieve']:
            return self.queryset.filter(status=1)
        else:
            return self.queryset

    def get_serializer_class(self):
        if self.action in ['comment']:
            return CommentSerializer
        else:
            return self.serializer_class

    def create(self, request, *args, **kwargs):
        # 允许修改post参数
        request.POST._mutable = True
        request.data['user'] = request.user.id
        return ModelViewSet.create(self, request, *args, **kwargs)

    def retrieve(self, request, *args, **kwargs):
        # 增加浏览量的操作
        # self.get_queryset()得到查询值
        # filter()过滤 通过id得到指定的文章
        # update()修改 F查询 得到字段的值
        self.get_queryset().filter(id=kwargs['pk']).update(page_view=F('page_view') + 1)
        return ModelViewSet.retrieve(self, request, *args, **kwargs)

    @action(methods=['get'], detail=True)
    def comment(self, request, pk):
        #         /articles/1/comments/
        #         得到指定文章的所有评论
        try:
            article = self.get_queryset().get(id=pk)
        except Article.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        #         得到文章的所有一级评论 父级评论为空的评论
        comments = article.comment_set.filter(parent_comment__isnull=True)
        # 分页器默认只会给到list方法使用，如果自定义的方法也需要使用分页器
        # 手动通过self.paginate_queryset传入查询集进行分页的操作
        comments_page=self.paginate_queryset(comments)
        # 传入的分页后的评论
        serializer = self.get_serializer(comments_page, many=True)
        return self.get_paginated_response(serializer.data)


class CommentViewSet(ModelViewSet):
    # 只能查看已经发布的文章的评论
    # 只能对已经发布的文章做评论的操作
    # 条件是文章的状态为发布状态 文章没有被删除
    # 没有被删除评论
    queryset = Comment.objects.filter(article__status=1, article__is_delete=False, is_delete=False)
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = MyPagination

    def get_serializer_class(self):
        if self.action in ['retrieve']:
            return SonCommentSerializer
        else:
            return self.serializer_class

    def create(self, request, *args, **kwargs):
        # 允许修改post参数
        request.POST._mutable = True
        request.data['user'] = request.user.id
        return ModelViewSet.create(self, request, *args, **kwargs)

    def retrieve(self, request, *args, **kwargs):
        # 得到当前评论的所有子级评论
        try:
            comment = self.get_queryset().get(id=kwargs['pk'])
        except Comment.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)
        comments_page=self.paginate_queryset(comment.parent_comment_set.all())
        serializer = self.get_serializer(comments_page, many=True)
        return self.get_paginated_response(serializer.data)
